#ifndef __M_ONLINE_H__
#define __M_ONLINE_H__

#include <mutex>
#include <unordered_map>
#include "util.hpp"


class online_manager {
private:
    std::mutex mutex;
    /*游戏大厅内用户uid和通信连接的映射表*/
    std::unordered_map<uint64_t, wsserver_t::connection_ptr> _hall_user;
    /*游戏房间内用户uid和通信连接的映射表*/
    std::unordered_map<uint64_t, wsserver_t::connection_ptr> _room_user;
public:
    online_manager(){}
    /*websocket链接建立时才会加入游戏大厅或游戏房间的在线用户管理，即哈希表*/
    void enter_game_hall(uint64_t uid, wsserver_t::connection_ptr &conn) {
        std::unique_lock<std::mutex> lock(mutex);
        _hall_user.insert(std::make_pair(uid, conn));
    }
    void enter_game_room(uint64_t uid, wsserver_t::connection_ptr &conn) {
        std::unique_lock<std::mutex> lock(mutex);
        _room_user.insert(std::make_pair(uid, conn));
    }
    void exit_game_hall(uint64_t uid) {
        std::unique_lock<std::mutex> lock(mutex);
        _hall_user.erase(uid);
    }
    void exit_game_room(uint64_t uid) {
        std::unique_lock<std::mutex> lock(mutex);
        _room_user.erase(uid);
    }
    /*根据uid判断是否在游戏大厅或游戏房间*/
    bool is_in_game_hall(uint64_t uid){
        std::unique_lock<std::mutex> lock(mutex);
        auto it = _hall_user.find(uid);
        return it != _hall_user.end();
    }
    bool is_in_game_room(uint64_t uid){
        std::unique_lock<std::mutex> lock(mutex);
        auto it = _room_user.find(uid);
        return it != _room_user.end();
    }
    /*通过uid获取连接*/ 
    wsserver_t::connection_ptr get_conn_from_hall(uint64_t uid) {
        std::unique_lock<std::mutex> lock(mutex);
        auto it = _hall_user.find(uid);
        if(it == _hall_user.end()){
            return wsserver_t::connection_ptr();
        }
        return it->second;
    }
    wsserver_t::connection_ptr get_conn_from_room(uint64_t uid) {
        std::unique_lock<std::mutex> lock(mutex);
        auto it = _room_user.find(uid);
        if(it == _room_user.end()){
            return wsserver_t::connection_ptr();
        }
        return it->second;
    }
};

#endif
